<?php
/**
 * @Author: anchen
 * @Date:   2017-10-04 14:59:06
 * @Last Modified by:   anchen
 * @Last Modified time: 2017-10-04 18:55:37
 */
defined('ACCESS_KEY9296')||exit('denied');

class CartModel extends Model{

    protected $table = 'cake';
    public function addToCart($cake_id, $Num=1)
    {
        if ($cake_id <= 0) {
            echo '请输入商品ID';
            exit;
        }

        //判断商品商品是否存在
        $cake = $this->db->getRow("SELECT cake_id,cake_price,cake_images FROM cake WHERE cake_id='$cake_id'");
        $cake['cake_id']||exit();


        //判断是否存在购物车
        @$_SESSION['cart']||$_SESSION['cart']=array();
        $data=$_SESSION['cart'];


        //判断购物车是否已有对应商品
        array_key_exists($cake['cake_id'], $data)
        ?
        $data[$cake['cake_id']]['num']+=$Num
        :
        $data[($cake['cake_id'])]=array('num'=>$Num+0,'price'=>$cake['cake_price'],'img'=>$cake['cake_images']);



        $_SESSION['cart']=$data;

    }

    public function delete($cake_id,$Num='all',$type=1){

        if($type!==1){
            $_SESSION['cart']=array();
            return 0;
        }

        if(empty($_SESSION['cart']) || !isset($_SESSION['cart'])){
            return 0;
        }


        $data=$_SESSION['cart'];

        if(array_key_exists($cake_id, $data)){
            $Num==='all'
            ?
            $data[$cake_id]['num']=0
            :
            $data[$cake_id]['num']-=$Num;
            $_SESSION['cart']=$data;
            return 1;
        }
        return 0;

    }


    public function showCart($type=1){
        if(empty($_SESSION['cart']) || !isset($_SESSION['cart'])){
            return array();
        }

        $data=$_SESSION['cart'];
        $arr=array();
        foreach ($data as $key=>$value){
            $value['num']>0 && $arr[$key]=$value;
        }
        $_SESSION['cart']=$arr;


        if($type==1){
            return $_SESSION['cart'];
        }
        else{
            $cake=array('classNum'=>0,'num'=>0,'price'=>0);
            foreach ($arr as $key=>$value){
                $cake['classNum']++;
                $cake['num']+=$value['num'];
                $cake['price']=$cake['price']+$value['num']*$value['price'];
            }
            return $cake;
        }
    }

}